package patrol.mobile.com.mobilepatrol.activity.office;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.media.MediaMetadataRetriever;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.lzy.imagepicker.ui.ImagePreviewDelActivity;
import com.lzy.imagepicker.view.CropImageView;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import butterknife.BindView;
import okhttp3.Call;
import patrol.mobile.com.mobilepatrol.R;
import patrol.mobile.com.mobilepatrol.activity.BaseActivity;
import patrol.mobile.com.mobilepatrol.activity.VideoPlayActivity;
import patrol.mobile.com.mobilepatrol.adapter.GlideImageLoader;
import patrol.mobile.com.mobilepatrol.adapter.ImagePickerAdapter;
import patrol.mobile.com.mobilepatrol.api.Urls;
import patrol.mobile.com.mobilepatrol.bean.AdviceDetailBean;
import patrol.mobile.com.mobilepatrol.bean.DeviceDetailImgBean;
import patrol.mobile.com.mobilepatrol.bean.UpImgInfoBean;
import patrol.mobile.com.mobilepatrol.manager.UserManager;
import patrol.mobile.com.mobilepatrol.picker.matisse.Matisse;
import patrol.mobile.com.mobilepatrol.picker.matisse.MimeType;
import patrol.mobile.com.mobilepatrol.picker.matisse.engine.GlideEngine;
import patrol.mobile.com.mobilepatrol.utils.CommonParamsHelper;
import patrol.mobile.com.mobilepatrol.utils.CommonUtil;
import patrol.mobile.com.mobilepatrol.utils.Constants;
import patrol.mobile.com.mobilepatrol.utils.FileUtil;
import patrol.mobile.com.mobilepatrol.utils.GsonUtil;
import patrol.mobile.com.mobilepatrol.utils.LuBanHelper;
import patrol.mobile.com.mobilepatrol.utils.SDFileHelper;
import patrol.mobile.com.mobilepatrol.utils.SPUtils;
import patrol.mobile.com.mobilepatrol.utils.StringUtils;
import patrol.mobile.com.mobilepatrol.utils.net.HttpCallBack2;
import patrol.mobile.com.mobilepatrol.utils.net.HttpSender;
import patrol.mobile.com.mobilepatrol.widget.dialog.SelectDialog;

import static patrol.mobile.com.mobilepatrol.activity.security.emergency.EmergencySaveCheck2Activity.REQUEST_CODE_VSELECT;

public class AdviceDetail2Activity extends BaseActivity implements ImagePickerAdapter.OnRecyclerViewItemClickListener {

    private static final String ADVICE_ID = "ADVICE_ID";
    private static final String TAG = "AdviceDetailActivity";
    @BindView(R.id.iv)
    ImageView iv;
    private ArrayList<ImageItem> selImageList;
    private ImagePickerAdapter adapter;
    public static final int IMAGE_ITEM_ADD = -1;
    public static final int REQUEST_CODE_SELECT = 100;
    public static final int REQUEST_CODE_PREVIEW = 101;
    private int limitSize = 4;
    @BindView(R.id.et_title)
    EditText etTitle;
    @BindView(R.id.et_content)
    EditText etContent;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.et_huifu)
    EditText etHuifu;
    @BindView(R.id.checkbox)
    CheckBox checkbox;
    @BindView(R.id.btn_submit)
    Button btnSubmit;
    private String id;
    private List<String> imgUUIDs = new ArrayList<>();
    private List<String> imgOldUUIDs = new ArrayList<>();
    private List<UpImgInfoBean> oldImgInfo = new ArrayList<>();
    private String videoPath = "";
    public static void show(Context context, String id) {
        Intent intent = new Intent(context, AdviceDetail2Activity.class);
        intent.putExtra(ADVICE_ID, id);
        context.startActivity(intent);
    }

    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_advice_detail2;
    }

    @Override
    public void initTitle() {
        super.initTitle();
        iv_back.setImageResource(R.mipmap.up_white);
        iv_back.setVisibility(View.VISIBLE);
        iv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                CommonUtil.exitActivityAndBackAnim(AdviceDetail2Activity.this, true);
            }
        });
        tv_center_title.setVisibility(View.VISIBLE);
        tv_center_title.setText("意见详情");
        String current_id = (String) SPUtils.get(Constants.current_id, "");
        Log.i(TAG, "requestData: " + current_id);
        String username = UserManager.getUser(current_id).username;
        String bmcode = UserManager.getUser(current_id).bmcode;
        String bmname = UserManager.getUser(current_id).bmname;
        String pw = UserManager.getUser(current_id).pw;
        String ryid = UserManager.getUser(current_id).ryid;
        String ryname = UserManager.getUser(current_id).ryname;
        String orgName = UserManager.getUser(current_id).orgName;
        String org_No = UserManager.getUser(current_id).org_No;
        String orgtype = UserManager.getUser(current_id).orgtype;

        Log.i(TAG, "requestData: " + username + "---" + bmcode + "---" + bmname + "---" + pw + "---" + ryid + "---" + ryname + "---" + orgName + "---" + org_No + "---" + orgtype + "---");

    }

    @Override
    public void initData() {
        super.initData();
        initImagePicker();
        selImageList = new ArrayList<>();
        adapter = new ImagePickerAdapter(this, selImageList, limitSize);
        adapter.setOnItemClickListener(this);
        recyclerView.setLayoutManager(new GridLayoutManager(this, limitSize));
        recyclerView.setHasFixedSize(true);
        recyclerView.setAdapter(adapter);
        id = getIntent().getStringExtra(ADVICE_ID);
        requestData();
    }

    private void requestData() {

        HttpSender sender = new HttpSender(this, baseUrl, Urls.ADVICE_ENTITY);
        HashMap<String, String> map = new HashMap<>();
        map.put("id", id);
        sender.requestPost(map, new HttpCallBack2(sender) {
            @Override
            public void onError(String code, Call call, Exception e) {

            }

            @Override
            public void onResponse(String code, String response, String attachList) {
                AdviceDetailBean adviceDetailBean = GsonUtil.GsonToBean(response, AdviceDetailBean.class);
                etTitle.setText(adviceDetailBean.getTitle());
                etContent.setText(adviceDetailBean.getContent());
                etHuifu.setText(adviceDetailBean.getReplayContent());
                List<DeviceDetailImgBean> deviceDetailImgBeans = GsonUtil.jsonToList(attachList, DeviceDetailImgBean.class);
                images = new ArrayList<>();
                SDFileHelper fileHelper = new SDFileHelper(AdviceDetail2Activity.this);

                for (DeviceDetailImgBean deviceDetailImgBean : deviceDetailImgBeans) {
                    String url = baseUrl + deviceDetailImgBean.getFilePath();
                    String replace = url.replace("\\", "/");

                    long currentTime = System.currentTimeMillis();
                    fileHelper.savePicture(currentTime + ".jpg", replace);
                    ImageItem imageItem = new ImageItem();
                    UpImgInfoBean upImgInfoBean = new UpImgInfoBean();
                    try {
                        String filePath = Environment.getExternalStorageDirectory().getCanonicalPath() + "/budejie/" + currentTime + ".jpg";
                        imageItem.path = filePath;
//                        Glide.with(AdviceDetail2Activity.this).load(new File(filePath)).into(iv);
                        selImageList.add(imageItem);
                        imgOldUUIDs.add(deviceDetailImgBean.getId());
                        upImgInfoBean.setId(deviceDetailImgBean.getId());
                        upImgInfoBean.setFileType(deviceDetailImgBean.getFileType());
                        upImgInfoBean.setContentType(deviceDetailImgBean.getContentType());
                        upImgInfoBean.setBusniessId(deviceDetailImgBean.getBusniessId());
                        oldImgInfo.add(upImgInfoBean);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                fileHelper.setOnFileSaveSuccessListener(new SDFileHelper.OnFileSaveSuccessListener() {
                    @Override
                    public void onFileSaveSuccess() {
                        adapter.setImages(selImageList);
                    }
                });

            }
        });
    }

    private void initImagePicker() {
        ImagePicker imagePicker = ImagePicker.getInstance();
        imagePicker.setImageLoader(new GlideImageLoader());   //设置图片加载器
        imagePicker.setShowCamera(true);                      //显示拍照按钮
        imagePicker.setCrop(true);                            //允许裁剪（单选才有效）
        imagePicker.setSaveRectangle(true);                   //是否按矩形区域保存
        imagePicker.setSelectLimit(4);              //选中数量限制
        imagePicker.setMultiMode(false);                      //多选
        imagePicker.setStyle(CropImageView.Style.RECTANGLE);  //裁剪框的形状
        imagePicker.setFocusWidth(800);                       //裁剪框的宽度。单位像素（圆形自动取宽高最小值）
        imagePicker.setFocusHeight(800);                      //裁剪框的高度。单位像素（圆形自动取宽高最小值）
        imagePicker.setOutPutX(1000);                         //保存文件的宽度。单位像素
        imagePicker.setOutPutY(1000);                         //保存文件的高度。单位像素
    }

    private void submit() {
        final HttpSender sender = new HttpSender(this, baseUrl, Urls.ADVICE_UP_LOAD);
        String title = CommonUtil.getText(etTitle);
        String content = CommonUtil.getText(etContent);
        if (StringUtils.isEmpty(title) || StringUtils.isEmpty(content)) {
            Toast.makeText(this, "请输入内容", Toast.LENGTH_SHORT).show();
            return;
        }
        String isChecked;
        if (checkbox.isChecked()) {
            isChecked = "是";
        } else {
            isChecked = "否";
        }
        HashMap<String, String> idDateBmnameMap = CommonParamsHelper.getIdDateBmnameMap();
        HashMap<String, Object> map = new HashMap<>();
        map.put("title", title);
        map.put("content", content);
        map.put("isNo", isChecked);
        map.put("auditFlag", "0");
        map.put("auditName", "未回复");
        map.putAll(idDateBmnameMap);
        HashMap<String, Object> map1 = new HashMap<>();
        map1.put("userAdvice", GsonUtil.map2Json(map));
        // TODO: 2018/10/23
        List<ImageItem> images = adapter.getImages();// all img
        List<UpImgInfoBean> upImgInfoBeanList = new ArrayList<>();//new info

        for (int i = 0; i < images.size() - oldImgInfo.size(); i++) {
            UpImgInfoBean imgInfoBean = new UpImgInfoBean();
            imgInfoBean.setBusniessId(idDateBmnameMap.get("id"));
            imgInfoBean.setContentType("userAdvice");
            imgInfoBean.setFileType("img");
            String uuid = UUID.randomUUID().toString();
            imgUUIDs.add(uuid);
            imgInfoBean.setId(uuid);
            upImgInfoBeanList.add(imgInfoBean);
        }
        oldImgInfo.addAll(upImgInfoBeanList);

        /*for (ImageItem image : images) {
            UpImgInfoBean imgInfoBean = new UpImgInfoBean();
            imgInfoBean.setBusniessId(idDateBmnameMap.get("id"));
            imgInfoBean.setContentType("userAdvice");
            imgInfoBean.setFileType("img");
            String uuid = UUID.randomUUID().toString();
            imgUUIDs.add(uuid);
            imgInfoBean.setId(uuid);
            upImgInfoBeanList.add(imgInfoBean);
        }*/
        map1.put("sysAttachmentsJson", GsonUtil.bean2Json(oldImgInfo));
        Log.i(TAG, "submit: " + GsonUtil.map2Json(map1));
        sender.postJson(GsonUtil.map2Json(map1), new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Log.i(TAG, "onResponse: " + e.toString());
                sender.dismissDialog();
                Toast.makeText(AdviceDetail2Activity.this, "提交失败", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onResponse(String response, int id) {
                sender.dismissDialog();
                Log.i(TAG, "onResponse: " + response);
//                finish();
                upImg();
            }
        });
    }


    @Override
    public void setListener() {
        btnSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                submit();
            }
        });
    }

    private void upImg() {
        if (selImageList != null && selImageList.size() != 0) {
            List<File> list = new ArrayList<>();
            List<ImageItem> images = adapter.getImages();
            for (ImageItem image : images) {
                File file = new File(image.path);
                list.add(file);
            }

            List<Map<String, String>> params = new ArrayList<>();
            for (UpImgInfoBean upImgInfoBean : oldImgInfo) {
                Map<String, String> map = new HashMap<>();
                map.put("id", upImgInfoBean.getId());
                map.put("type", "userAdvice");
                params.add(map);
            }

            LuBanHelper luBanHelper = new LuBanHelper(AdviceDetail2Activity.this, list, params);
            luBanHelper.compression(new StringCallback() {
                @Override
                public void onError(Call call, Exception e, int id) {
                    Log.i(TAG, "onResponse: " + e);
                }

                @Override
                public void onResponse(String response, int id) {
                    Log.i(TAG, "onResponse: " + response);
                    try {
                        JSONObject jsonObject = new JSONObject(response);
                        if (jsonObject.getInt("state") == 200) {
                            finish();
                            Toast.makeText(AdviceDetail2Activity.this, "上传成功！", Toast.LENGTH_SHORT).show();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    }

    ArrayList<ImageItem> images = null;
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null) {
            switch (resultCode) {
                case ImagePicker.RESULT_CODE_ITEMS:
                    //添加图片返回
                    if (requestCode == REQUEST_CODE_SELECT) {
                        images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                        if (images != null) {
                            for (int i = 0; i < images.size(); i++) {
                                images.get(i).mimeType = "image";
                            }
                            selImageList.addAll(images);
                            adapter.setImages(selImageList);
                        }
                    }
                    break;
                case ImagePicker.RESULT_CODE_BACK:
                    //预览图片返回
                    if (requestCode == REQUEST_CODE_PREVIEW) {
                        images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_IMAGE_ITEMS);
                        if (images != null) {
                            selImageList.clear();
                            selImageList.addAll(images);
                            adapter.setImages(selImageList);
                        }
                    }
                    break;
                case RESULT_OK:
                    //选择视频返回
                    if (requestCode == REQUEST_CODE_VSELECT) {
                        List<String> videoUrls = Matisse.obtainPathResult(data);
                        Log.e("videoUrls", videoUrls.get(0));
                        videoPath = videoUrls.get(0);
                        MediaMetadataRetriever retr = new MediaMetadataRetriever();
                        retr.setDataSource(videoPath);
                        //获取第一帧图像的bitmap对象
                        Bitmap bitmap = retr.getFrameAtTime();
                        String imgUrl = FileUtil.saveImg2Gallery(this, bitmap,
                                System.currentTimeMillis() / 1000 + "");
                        ImageItem imageItem = new ImageItem();
                        imageItem.path = imgUrl;
                        imageItem.name = videoPath;
                        imageItem.mimeType = "video";
                        selImageList.add(imageItem);
                        adapter.setImages(selImageList);

                    }
                    break;
            }
        }
    }

    @Override
    public void onItemClick(View view, int position) {
        switch (position) {
            case IMAGE_ITEM_ADD:
                List<String> names = new ArrayList<>();
                names.add("拍照");
                names.add("相册");
                names.add("视频");
                showDialog(new SelectDialog.SelectDialogListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        switch (position) {
                            case 0: // 直接调起相机
                                /**
                                 * 0.4.7 目前直接调起相机不支持裁剪，如果开启裁剪后不会返回图片，请注意，后续版本会解决
                                 *
                                 * 但是当前直接依赖的版本已经解决，考虑到版本改动很少，所以这次没有上传到远程仓库
                                 *
                                 * 如果实在有所需要，请直接下载源码引用。
                                 */
                                //打开选择,本次允许选择的数量
                                ImagePicker.getInstance().setSelectLimit(limitSize - selImageList.size());
                                Intent intent = new Intent(AdviceDetail2Activity.this, ImageGridActivity.class);
                                intent.putExtra(ImageGridActivity.EXTRAS_TAKE_PICKERS, true); // 是否是直接打开相机
                                startActivityForResult(intent, REQUEST_CODE_SELECT);
                                break;
                            case 1:
                                //打开选择,本次允许选择的数量
                                ImagePicker.getInstance().setSelectLimit(limitSize - selImageList.size());
                                Intent intent1 = new Intent(AdviceDetail2Activity.this, ImageGridActivity.class);
                                /* 如果需要进入选择的时候显示已经选中的图片，
                                 * 详情请查看ImagePickerActivity
                                 * */
                                startActivityForResult(intent1, REQUEST_CODE_SELECT);
                                break;
                            case 2:
                                if (!(checkPermission(Manifest.permission.CAMERA))) {
                                    ActivityCompat.requestPermissions(AdviceDetail2Activity.this, new String[]{Manifest.permission.CAMERA}, ImageGridActivity.REQUEST_PERMISSION_CAMERA);
                                } else {
                                    Matisse.from(AdviceDetail2Activity.this)
                                            .choose(MimeType.ofVideo())
                                            .showSingleMediaType(true)
                                            .theme(R.style.Matisse_Dracula)
                                            .countable(false)
                                            .maxSelectable(1)
                                            .imageEngine(new GlideEngine())
                                            .forResult(REQUEST_CODE_VSELECT);
                                }

                                break;
                            default:
                                break;
                        }

                    }
                }, names);
                break;
            default:
                if (adapter.getImages().get(position).mimeType.equals("image")) {
                    //打开预览
                    Intent intentPreview = new Intent(this, ImagePreviewDelActivity.class);
                    intentPreview.putExtra(ImagePicker.EXTRA_IMAGE_ITEMS, (ArrayList<ImageItem>) adapter.getImages());
                    intentPreview.putExtra(ImagePicker.EXTRA_SELECTED_IMAGE_POSITION, position);
                    intentPreview.putExtra(ImagePicker.EXTRA_FROM_ITEMS, true);
                    startActivityForResult(intentPreview, REQUEST_CODE_PREVIEW);
                } else {
                    Intent intentPreview = new Intent(this, VideoPlayActivity.class);
                    intentPreview.putExtra("videopath", adapter.getImages().get(position).name);
                    startActivity(intentPreview);
                }
                break;
        }
    }

    private SelectDialog showDialog(SelectDialog.SelectDialogListener listener, List<String> names) {
        SelectDialog dialog = new SelectDialog(this, R.style
                .transparentFrameWindowStyle,
                listener, names);
        if (!this.isFinishing()) {
            dialog.show();
        }
        return dialog;
    }
}
